package com.gid.rcflightlogger;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class BatteryBrowseActivity extends BaseActivity {

	private class BatteryData
	{
		public Battery mBattery;
		private int mCyclesCount;
		private int mRunTime; //seconds
		
		BatteryData(Battery b)
		{
			mBattery = b;
			mCyclesCount = 0;
			mRunTime = 0;
			
			//load cycle data from DB
			List<Cycle> cycles = mBattery.getCycles(getApplicationContext()).orderBy("mDate").toList();
			for (Cycle c : cycles)
			{
				mCyclesCount += c.getCount();
				mRunTime += c.getDuration();
			}
		}
		
		public int getCyclesCount()
		{
			return mCyclesCount;
		}
		
		public int getRunTime()
		{
			return mRunTime;
		}
	};
	
	private List<BatteryData> mBatteryData;
	
	public static final int REQUEST_CODE_ADD = 1;
	public static final int REQUEST_CODE_EDIT = 2;
	
	private TableLayout mTableLayout;
	private Button mAdd;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_batterybrowse);
        mCurrentMenuID = R.id.menu_main_inventory_batteries;
        mTableLayout = (TableLayout) findViewById(R.id.batterybrowse_table);
        mBatteryData = new ArrayList<BatteryData>();
        mAdd = (Button) findViewById(R.id.batterybrowse_btn_add);
        mAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				spawnBatteryEditor(REQUEST_CODE_ADD, 0);
			}
		});
	}
	
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }
	
	private void loadData() {
		//reload data from database
		List<Battery> allbatteries = Battery.objects(getApplicationContext()).all().orderBy("-mStatus").toList();
		mBatteryData.clear();
		
		for (Battery b : allbatteries)
		{
			BatteryData bd = new BatteryData(b);
			mBatteryData.add(bd);
		}
		
		//repopulate table
		mTableLayout.removeViews(2, mTableLayout.getChildCount() - 2); //keep the header and border
		
		for (BatteryData bd : mBatteryData) 
		{
			TableRow tr;
			TextView tv1, tv2, tv3, tv4, tv5;

			tr = (TableRow) getLayoutInflater().inflate(R.layout.layout_batterybrowse_row, null);
			// Fill out cells
			tv1 = (TextView) tr.findViewById(R.id.batterybrowse_col_name);
			tv1.setGravity(Gravity.LEFT);
			tv1.setText(bd.mBattery.getTag());
			
			tv2 = (TextView) tr.findViewById(R.id.batterybrowse_col_age);
			tv2.setGravity(Gravity.RIGHT);
			tv2.setText(myUtils.makeAgeStr(bd.mBattery.getPurchaseDate()));
			
			tv3 = (TextView) tr.findViewById(R.id.batterybrowse_col_cost);
			tv3.setGravity(Gravity.RIGHT);
			tv3.setText(Double.toString(bd.mBattery.getCost()));
   	    
			tv4 = (TextView) tr.findViewById(R.id.batterybrowse_col_cycles);
			tv4.setGravity(Gravity.RIGHT);
			tv4.setText(Integer.toString(bd.getCyclesCount())); 
			
			tv5 = (TextView) tr.findViewById(R.id.batterybrowse_col_runtime);
			tv5.setGravity(Gravity.RIGHT);
			tv5.setText(myUtils.Duration2Str(bd.getRunTime(), true)); 
			
			//fade text if the item is deactivated
			if (!bd.mBattery.getStatus())
			{
				tv1.setTextColor(0x66666666);
				tv2.setTextColor(0x66666666);
				tv3.setTextColor(0x66666666);
				tv4.setTextColor(0x66666666);
				tv5.setTextColor(0x66666666);
			}
			tr.setPadding(0, 2, 0, 0);	
			tr.setId(bd.mBattery.getId());
			tr.setClickable(true); 
			tr.setOnTouchListener(mRowOnTouchListener);
			tr.setOnLongClickListener(mRowOnLongClickListener);
			tr.setFocusable(true);
			tr.setOnFocusChangeListener(mRowOnFocusChangeListener);
			
			mTableLayout.addView(tr);
			
			//table's horizontal line
			View ruler = new View(getApplicationContext());
			ruler.setBackgroundColor(0x88909090);
			mTableLayout.addView(ruler,new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 1));
		}
	}
	
	//changes highlighted state of a given table row, by adding or removing bg color
	private void highlightTableRow(TableRow r, boolean highlighted)
	{
		if (highlighted)
		{
			r.setBackgroundColor(Color.rgb(247, 125, 0)); //android default list selector bg color
			r.invalidate();
		}
		else
		{
			r.setBackgroundResource(0);
			r.invalidate();
		}
	}
	
	private void spawnBatteryEditor (int request_code, int id)
    {
		Intent i = new Intent(this, BatteryEditActivity.class);
		
		if (request_code == REQUEST_CODE_EDIT && id != 0)
    	{
			i.putExtra(Battery.ID_LABEL, id);
			//myUtils.makeToast(getApplicationContext(), "id = " + Integer.toString(id));
    	}
		startActivityForResult(i, request_code);
    }
	// ====================================================
	// Various isteners
	// ====================================================
	private TableRow.OnTouchListener mRowOnTouchListener = new TableRow.OnTouchListener()
    {
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			final int action = event.getAction();
			switch (action & MotionEvent.ACTION_MASK)
			{
				case MotionEvent.ACTION_UP:
				case MotionEvent.ACTION_CANCEL:
				case MotionEvent.ACTION_OUTSIDE:
				//case MotionEvent.ACTION_MOVE:
					highlightTableRow((TableRow) v, false);
					break;
				default:
					highlightTableRow((TableRow) v, true);
			}
			return false;
		}
    };
    
    private TableRow.OnLongClickListener mRowOnLongClickListener = new TableRow.OnLongClickListener()
    {
    	@Override
		public boolean onLongClick(View v) {
    		spawnBatteryEditor(REQUEST_CODE_EDIT, v.getId());
			return true;
		}
    };
    
    private TableRow.OnFocusChangeListener mRowOnFocusChangeListener = new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			highlightTableRow((TableRow) v, hasFocus);			
		}
    };
}
